﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Text;

namespace DomainDriver.Presentation.Silverlight.Base
{
    public class DomainControllerBase : IDomainController
    {
        private IDomainView m_View;

        public event RefreshRequestHandler RefreshRequested;

        public DomainControllerBase()
        {
            m_View = null;
        }

        public bool HasView
        {
            get { return m_View != null; }
        }

        public IDomainView View
        {
            get { return m_View; }
            set
            {
                if (HasView)
                { throw new InvalidOperationException("Can only set View once."); }
                if (value == null)
                { return; }

                m_View = value;
            }
        }

        public bool HasApplicationObject
        {
            get { return UiConfiguration.HasApplicationObject; }
        }

        public IApplicationObject ApplicationObject
        {
            get { return UiConfiguration.ApplicationObject; }
        }

        public virtual bool IsReadyToDisplay
        {
            get { return true; }
        }

        protected void DispatchRefreshRequestedEvent()
        { DispatchRefreshRequestedEvent(null, null); }

        protected void DispatchRefreshRequestedEvent(string requestedMethodName)
        { DispatchRefreshRequestedEvent(requestedMethodName, null); }

        protected void DispatchRefreshRequestedEvent(OperationBase completedOperation)
        { DispatchRefreshRequestedEvent(null, completedOperation); }

        protected void DispatchRefreshRequestedEvent(string requestedMethodName, OperationBase completedOperation)
        {
            if (RefreshRequested == null)
            { return; }
            RefreshRequested(this, new RefreshRequestEventArgs(requestedMethodName, completedOperation));
        }

        protected virtual void OnSubscribeToApplicationLevelEvents()
        { }

        public void Dispose()
        {
            OnDispose();
            m_View = null;
        }

        public virtual void OnDispose()
        { }
    }
}